package campshop.daos;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import campshop.models.TradeInfo;
public class TradeInfoDao extends JdbcDaoSupport{
	public long addTradeInfo(TradeInfo ti)
	{
		String sql = "insert into " +
				"tbl_trade_info (cs_uId, oi_uId, ti_dCreateDate, gi_uGoodsId, ti_uGoodsNum, ti_fMoney)" +
				" values (?, ?, ?, ?, ?, ?)";
		if(super.getJdbcTemplate().update(sql, ti.getuUserId(), ti.getuOrderId(), ti.getdCreateDate(), ti.getuGoodsId()
				, ti.getuGoodsNum(), ti.getfMoney())>0){
			return super.getJdbcTemplate().queryForInt("select max(ti_uId) from tbl_trade_info");
		}else return 0L;
	}
	
	public boolean delTradeInfo(long uId)
	{
		String sql = "delete from tbl_trade_info where ti_uId = ?";
		if(super.getJdbcTemplate().update(sql, uId)>0) return true;
		return false;
	}
	
	public TradeInfo getTradeInfo(long uId)
	{
		String sql = "select * from tbl_trade_info where ti_uId=" + uId;
		return (TradeInfo)super.getJdbcTemplate().queryForObject(sql, new TradeInfoRowMapper());
	}
	
	class TradeInfoRowMapper implements RowMapper<TradeInfo>{
		@Override
		public TradeInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
			TradeInfo ti = new TradeInfo();
			ti.setuId(rs.getLong("ti_uId"));
			ti.setuUserId(rs.getLong("cs_uId"));
			ti.setuOrderId(rs.getLong("oi_uId"));
			ti.setdCreateDate(rs.getDate("ti_dCreateDate"));
			ti.setuGoodsId(rs.getLong("gi_uGoodsId"));
			ti.setuGoodsNum(rs.getLong("ti_uGoodsNum"));
			ti.setfMoney(rs.getFloat("ti_fMoney"));
			return ti;
		}	
	}
}
